# MadSnake - A snake game
# Copyright (C) 2020-2021  zhiqiang.bzq
#
# See LICENSE. And if you have interest in this project, join us.
#
# zhiqiang.bzq
# bzq23@foxmail.com

from common import *
from item import *
import time
import random

class Ground(object):
  def __init__(self, size):
    self.size_ = size
    self.item_map_ = {}
    self.item_generate_time_ = {}
    self.InitilizeGround()
    self.last_gen_item_time_ = time.time()
    self.item_last_time_ = 30
    self.item_blink_last_time_ = 5

  def Size(self):
    return self.size_

  def OnGenerating(self, body_points, good_interval):
    self.Cleanup()
    if time.time() < self.last_gen_item_time_ + good_interval: return
    self.GenerateItem(body_points)

  def OnEvent(self):
    pass
    
  def ItemMap(self):
    return self.item_map_

  def InitilizeGround(self):
    for y in range(self.size_.height):
      self.item_map_[(0, y)] = Item(Item.WALL, Point(0, y))
      self.item_map_[(self.size_.width - 1, y)] = Item(Item.WALL, Point(self.size_.width - 1, y))
    for x in range(self.size_.width):
      self.item_map_[(x, 0)] = Item(Item.WALL, Point(x, 0))
      self.item_map_[(x, self.size_.height - 1)] = Item(Item.WALL, Point(x, self.size_.height - 1))

  def GenerateItem(self, exclude_points):
    # TODO: It's a stupy way to avoid collision.
    # Maybe we should not generate when collision occurs ?
    x = random.randint(1, self.size_.width - 2)
    y = random.randint(1, self.size_.height - 2)
    if (x, y) in exclude_points or (x, y) in self.item_map_:
      return self.GenerateItem(exclude_points)
    item = Item.GenerateRandomItem(Point(x, y))
    self.item_map_[(x, y)] = item
    self.last_gen_item_time_ = time.time()
    self.item_generate_time_[(x, y)] = self.last_gen_item_time_ + self.item_last_time_
    return item

  def RemoveItem(self, loc):
    # we can only remove item which generated.
    if loc in self.item_generate_time_:
      self.item_map_.pop(loc)
      self.item_generate_time_.pop(loc)

  def Cleanup(self):
    now = time.time()
    loc_need_delete = []
    for k, t in self.item_generate_time_.items():
      if now >= t and t > 0.:
        loc_need_delete.append(k)
    for k in loc_need_delete:
      self.RemoveItem(k)

  def ColorForLocation(self, loc):
    if loc not in self.item_map_: return None
    if loc in self.item_generate_time_ and self.item_generate_time_[loc] - time.time() < self.item_blink_last_time_:
      if random.random() < 0.5:
        return Color.BLACK
    return self.item_map_[loc].Color()

